from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
import os
from datetime import timedelta

# 初始化扩展
db = SQLAlchemy()
login_manager = LoginManager()

def create_app(config_name=None):
    app = Flask(__name__)
    
    # 基本配置
    app.config['SECRET_KEY'] = os.urandom(24)
    app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=2)
    
    # 数据库配置
    app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@127.0.0.1:3306/aiot'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    
    # 初始化扩展
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'
    login_manager.login_message = '请先登录'
    login_manager.login_message_category = 'info'
    
    # 注册蓝图
    from app.main import main as main_blueprint
    from app.auth import auth as auth_blueprint
    from .device import device as device_blueprint
    from app.analysis import analysis as analysis_blueprint
    from app.water import water as water_blueprint
    from .network import network as network_blueprint
    from .settings import settings as settings_blueprint
    
    app.register_blueprint(main_blueprint)
    app.register_blueprint(auth_blueprint, url_prefix='/auth')
    app.register_blueprint(device_blueprint)
    app.register_blueprint(analysis_blueprint)
    app.register_blueprint(water_blueprint)
    app.register_blueprint(network_blueprint)
    app.register_blueprint(settings_blueprint)
    
    # 创建数据库表
    with app.app_context():
        db.create_all()
    
    return app 